<template>
  <div class="user-edit">
    <h2>编辑人员信息</h2>
    <el-form ref="userForm" :model="user" label-width="100px">
      <el-form-item label="姓名">
        <el-input v-model="user.name"></el-input>
      </el-form-item>
      <el-form-item label="年龄">
        <el-input v-model="user.age"></el-input>
      </el-form-item>
      <el-form-item label="身份证号">
        <el-input v-model="user.idCard"></el-input>
      </el-form-item>
      <el-form-item label="证件照片">
        <img :src="user.photoUrl" alt="证件照片" class="photo-preview" />
        <el-upload
            class="upload-photo"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
        >
          <el-button size="small" type="primary">上传证件照片</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'UserEdit',
  data() {
    return {
      user: {
        id: '',
        name: '',
        age: '',
        idCard: '',
        photoUrl: ''
      }
    };
  },
  mounted() {
    const userId = this.$route.params.id;
    this.fetchUser(userId);
  },
  methods: {
    fetchUser(userId) {
      axios.get(`http://localhost:8083/users/${userId}`)
          .then(response => {
            this.user = response.data;
          })
          .catch(error => {
            console.error("获取用户信息失败", error);
          });
    },
    saveUser() {
      axios.put(`http://localhost:8083/users/${this.user.id}`, this.user)
          .then(() => {
            this.$router.push({ name: 'userManagement' });
          })
          .catch(error => {
            console.error("更新用户信息失败", error);
          });
    },
    handleAvatarSuccess(response, file) {
      this.user.photoUrl = URL.createObjectURL(file.raw);
      console.log('上传的文件:', file, response);
    }
  }
};
</script>

<style scoped>
.user-edit {
  width: 400px;
  margin: 0 auto;
}
.photo-preview {
  width: 150px;
  height: 150px;
  margin-bottom: 10px;
}
.upload-photo {
  display: inline-block;
}
</style>
